package org.droid.campusorder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import org.droid.R;
import org.droid.campusorder.action.RespGetCatDishAction;
import org.droid.campusorder.action.RespGetShopCatAction;
import org.droid.campusorder.adapter.ListViewAdapter;
import org.droid.campusorder.adapter.ShopCatAdapter;
import org.droid.campusorder.bean.DishesBean;
import org.droid.campusorder.bean.RespCatDishBean;
import org.droid.campusorder.bean.RespShopCatBean;
import org.droid.campusorder.common.Config;
import org.droid.campusorder.common.Debug;
import org.droid.campusorder.common.GlobalData;
import org.droid.campusorder.manager.DownManager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DishesListActivity extends MyActivity {
	private Button getShopCatBtn; // 切换类别的Button
	private Button nextBtn; // 下一步
	private Button backBtn; // 返回
	private ImageView orderedImv;// 显示已点的ImageView
	private TextView totalPriceTv; // 显示总价的TextView
	private LinearLayout linearLayout; // 包裹类别ListView的LinearLayout
	private ListView shopCatList; // Dish类别ListView
	private ListView dishesList; // Dish ListView
	private Animation scaleStartAnimation; // 类别切换开始动画对象
	private Animation scaleEndAnimation; // 类别切换结束动画对象
	private Animation totalPriceStartAnimation; // 显示已点动画对象
	private Animation totalPriceEndAnimation; // 显示已点动画对象
	private ListViewAdapter listViewAdapter; // 装载Dish信息adapter
	private List<DishesBean> listItems; // Dish ListView的列表项
	private List<DishesBean> orderList; // 已点的菜
	private HashMap<String, String> map;
	private ArrayList<HashMap<String, String>> list; // 填充到Dish类别中的数据源
	private ShopCatAdapter shopCatAdapter; // 装载Dish类别信息adapter
	private RespGetShopCatAction respGetShopCatAction; // 请求类别响应器
	private RespGetCatDishAction respGetCatDishAction; // 请求Dish响应器
	private RespShopCatBean rscb; // 类别响应Bean
	private RespCatDishBean rcdb; // Dish响应Bean
	private Hashtable<String, String> ht; // 装载网络请求参数的Hashtable
	private DishesAsyncTask dishesAsyncTask; // 异步下载对象
	private double totalPrice = 0.0; // 总价
	private static int catId = 0; // 类别ID
	private static int position = -1; // 类别List中点击的类别对应的位置
	private boolean flag;// 标识List中数据是否属于第一个类别，true为第一个类别
	private Debug debug;
	private String[] dishPicPaths; // Dish图片在SD卡中的路径

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_dishes);
		/* 初始化 */
		debug = new Debug("DishesListActivity");
		dishesAsyncTask = new DishesAsyncTask();
		linearLayout = (LinearLayout) findViewById(R.id.cat_linearLayout);
		getShopCatBtn = (Button) findViewById(R.id.get_shop_cat_btn);
		nextBtn = (Button) findViewById(R.id.next_btn);
		backBtn = (Button) findViewById(R.id.back_to_main_btn);
		shopCatList = (ListView) findViewById(R.id.shop_cat_lv);
		dishesList = (ListView) findViewById(R.id.dishes_lv);
		orderedImv = (ImageView) findViewById(R.id.ordered_imv);
		totalPriceTv = (TextView) findViewById(R.id.total_price_tv);
		shopCatAdapter = new ShopCatAdapter(this);

		// 获取动画对象
		scaleStartAnimation = AnimationUtils.loadAnimation(this,
				R.anim.scale_start);
		scaleEndAnimation = AnimationUtils
				.loadAnimation(this, R.anim.scale_end);
		totalPriceStartAnimation = AnimationUtils.loadAnimation(this,
				R.anim.total_price_scale_start);
		totalPriceEndAnimation = AnimationUtils.loadAnimation(this,
				R.anim.total_price_scale_end);

		// 此处发请求到服务器获取dishes信息
		flag = true; // 默认显示类别为第一个类别

		handler.post(reqCatThread);
		listViewAdapter = new ListViewAdapter(this); // 创建适配器
		orderList = new ArrayList<DishesBean>(6); // 初始化已点菜单，默认创建容量为6的ArrayLis

		setListener();

		shopCatList.setAdapter(shopCatAdapter);
		dishesList.setAdapter(listViewAdapter);
	}

	// 10.3 重构,侦听器写到这
	public void setListener() {
		getShopCatBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (linearLayout.getVisibility() == View.VISIBLE) {
					handler.post(updateViewThread);
				}
				initCatList();
			}
		});

		nextBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (orderList.size() != 0) {
					GlobalData.orderList = orderList;

					for (int i = 0; i < orderList.size(); i++) {
						debug.debug("获得的菜：" + orderList.get(i).getName());
					}
					Intent intent = new Intent();// 此处还需传店铺电话号码
					intent.setClass(getApplicationContext(),
							OrderActivity.class);
					startActivity(intent);
				} else {
					Toast.makeText(getApplicationContext(), "请选择您想点的菜",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {	

			}
		});

		shopCatList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (linearLayout.getVisibility() == View.VISIBLE) {
							handler.post(updateViewThread);
						}
						debug.debug("cat:"
								+ GlobalData.rscb.getCatBeanList().get(arg2)
										.getName()
								+ "\t id:"
								+ GlobalData.rscb.getCatBeanList().get(arg2)
										.getId());
						catId = GlobalData.rscb.getCatBeanList().get(arg2)
								.getId();
						position = arg2;
						// 点击类别
						handler.post(reqDishesThread);
					}

				});
		dishesList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (linearLayout.getVisibility() == View.VISIBLE) {
							handler.post(updateViewThread);
						}
						// 显示dishes详情，选择发送短信或者拨打电话
						boolean b = listViewAdapter.changeView(arg2);
						/**
						 * 发handler，更新界面totalPriceTv.setText("");
						 */
						updateTotalPrice(arg2, b);
					}
				});
	}

	private void updateTotalPrice(int position, boolean b) {
		DishesBean orderDish = null;
		orderDish = getListItems().get(position);
		if (b) { // 已选
			totalPrice += Double.parseDouble(orderDish.getPrice());
			orderList.add(orderDish);
		} else { // 撤销选择
			totalPrice -= Double.parseDouble(orderDish.getPrice());
			orderList.remove(orderDish);
		}

		handler.post(updateTotalPrice);
	}

	/**
	 * 初始化OrderItem信息
	 */
	private List<DishesBean> getListItems() {
		if (flag && GlobalData.rscb != null) {
			listItems = GlobalData.rscb.getDishesBeanList();
			/*
			 * for (int i = 0;i < listItems.size();i++){
			 * debug.debug("旧的ListItem："
			 * +listItems.get(i).getName()+"pic:"+listItems.get(i).getPic()); }
			 */
			return listItems;
		} else if (!flag && GlobalData.rcdb != null) {
			listItems = GlobalData.rcdb.getDishesBeanList();
			/*
			 * for (int i = 0;i < listItems.size();i++){
			 * debug.debug("新的ListItem："
			 * +listItems.get(i).getName()+"pic:"+listItems.get(i).getPic()); }
			 */
			return listItems;
		} else {
			handler.sendEmptyMessage(0);
			return null;
		}
	}

	private void initCatList() {
		linearLayout.setVisibility(View.VISIBLE);
		linearLayout.startAnimation(scaleStartAnimation);
		if (list == null) {
			list = new ArrayList<HashMap<String, String>>();
		} else {
			list.removeAll(list);
		}
		/* 循环获取cat信息 */
		for (int i = 0; i < GlobalData.rscb.getCatBeanList().size(); i++) {
			map = new HashMap<String, String>();
			map.put("cat", GlobalData.rscb.getCatBeanList().get(i).getName());
			list.add(map);
		}
		// 发handler更新界面
		handler.sendEmptyMessage(2);
	}

	class DialogOnClickListener implements DialogInterface.OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			DishesListActivity.this.finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (linearLayout.getVisibility() == View.GONE) {
			return super.onKeyDown(keyCode, event);
		} else if (linearLayout.getVisibility() == View.VISIBLE
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			handler.post(updateViewThread);
		}

		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (linearLayout.getVisibility() == View.VISIBLE) {
			handler.post(updateViewThread);
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 用Handler来更新UI
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				debug.debug("出错~~");
				new AlertDialog.Builder(DishesListActivity.this)
						.setTitle("出错啦~").setMessage("请检查网络连接！")
						.setPositiveButton("确定", new DialogOnClickListener())
						.show();
				break;
			case 1:
				// 显示第一个类别下的Dish，类别的名称，异步下载显示Dish图片
				if (flag && GlobalData.rscb != null) {
					getShopCatBtn.setText(GlobalData.rscb.getCatBeanList()
							.get(0).getName());
					setDishLogoSrc(GlobalData.rscb.getDishesBeanList().size());
					if (dishesAsyncTask != null) {
						dishesAsyncTask.cancel(true);
					}
					dishesAsyncTask = new DishesAsyncTask();
					listViewAdapter.setDishPicPaths(dishPicPaths);
					dishesAsyncTask.execute("Start DownLoad");
				} else if (!flag && GlobalData.rcdb != null) {// 任意类别下的Dish
					getShopCatBtn.setText(GlobalData.rscb.getCatBeanList()
							.get(position).getName());
					setDishLogoSrc(GlobalData.rcdb.getDishesBeanList().size());
					if (dishesAsyncTask != null) {
						dishesAsyncTask.cancel(true);
					}
					dishesAsyncTask = new DishesAsyncTask();
					listViewAdapter.setDishPicPaths(dishPicPaths);
					dishesAsyncTask.execute("New Start DownLoad");
				}

				listViewAdapter.setListItems(getListItems());
				listViewAdapter.notifyDataSetChanged();
				/**/
				break;
			case 2:
				shopCatAdapter.setList(list);
				shopCatAdapter.notifyDataSetChanged();
				break;
			}
		}
	};

	/**
	 * 请求服务器商户类别和第一个分类
	 */
	Runnable reqCatThread = new Runnable() {
		@Override
		public void run() {
			// 发送请求到服务器获取店铺Dish类别及第一个类别中的Dish信息
			respGetShopCatAction = new RespGetShopCatAction(
					getApplicationContext());
			ht = new Hashtable<String, String>();
			// 请求参数
			ht.put("forword", "GetShopCat");
			ht.put("shopId", "1"); // shopId整合时再GlobalData中取
			try {
				debug.debug("到这了！");
				// 发送请求获取响应解析并保存到GlobalData中
				rscb = (RespShopCatBean) respGetShopCatAction
						.getMsgFromNetwork(null, Config.SubConfig.Req, ht);
				GlobalData.rscb = rscb;
				handler.sendEmptyMessage(1);
			} catch (Exception e) {
				debug.debug("这里！");
				handler.sendEmptyMessage(0);
				// e.printStackTrace();
			} finally {
				ht.clear();
				handler.removeCallbacks(reqCatThread);
			}
		}

	};

	Runnable reqDishesThread = new Runnable() {
		@Override
		public void run() {
			try {
				if (respGetCatDishAction == null) {
					respGetCatDishAction = new RespGetCatDishAction(
							getApplicationContext());
				}
				if (ht == null) {
					ht = new Hashtable<String, String>();
				}
				ht.put("forword", "GetCatDish");
				ht.put("shopId", "1");
				ht.put("catId", String.valueOf(catId));
				ht.put("page", "1");
				
				rcdb = (RespCatDishBean) respGetCatDishAction
						.getMsgFromNetwork(null, Config.SubConfig.Req, ht);
				GlobalData.rcdb = rcdb;
				
				if (0 == position) {// 第一个类别
					flag = true;
				} else {// 不是第一个类别
					flag = false;
				}
				handler.sendEmptyMessage(1);
			} catch (Exception e) {
				handler.sendEmptyMessage(0);
			} finally {
				ht.clear();
				respGetCatDishAction = null;
			}

		}

	};

	/**
	 * 更新界面，启动shopCatList隐藏动画
	 */
	Runnable updateViewThread = new Runnable() {
		@Override
		public void run() {
			linearLayout.startAnimation(scaleEndAnimation);
			linearLayout.setVisibility(View.GONE);
		}

	};

	/**
	 * 更新界面，启动OrderedImv启动隐藏动画
	 */
	Runnable updateTotalPrice = new Runnable() {
		@Override
		public void run() {
			totalPriceTv.setText(String.valueOf(totalPrice));
		}

	};

	private class DishesAsyncTask extends AsyncTask<String, Integer, Bitmap> {
		File file;

		@Override
		protected Bitmap doInBackground(String... params) {

			if (flag && GlobalData.rscb != null) {
				for (int i = 0; i < GlobalData.rscb.getDishesBeanList().size(); i++) {
					downImageAndUpdateView(GlobalData.rscb.getDishesBeanList()
							.get(i), i);
				}
			} else if (!flag && GlobalData.rcdb != null) {
				for (int i = 0; i < GlobalData.rcdb.getDishesBeanList().size(); i++) {
					downImageAndUpdateView(GlobalData.rcdb.getDishesBeanList()
							.get(i), i);
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			listViewAdapter.notifyDataSetChanged();
		}

		public void downImageAndUpdateView(DishesBean db, int i) {
			String fileDir = GlobalData.dirPath + "Dish/";
			File fileFolder = new File(fileDir);
			if (!fileFolder.exists()) {
				fileFolder.mkdirs();
			}
			String imagePath = fileDir
					+ DownManager.getImageFileName(db.getPic());
			file = new File(imagePath);
			if (!file.exists()) {// 若文件存在则不下载
				debug.debug("开始下载dish图片！！！");
				debug.debug("Strat-->>download file:" + imagePath);
				try {
					DownManager.downImage(db.getPic(), imagePath);
					publishProgress(i);
				} catch (Exception e) {
					debug.debug(e.getMessage());
					e.printStackTrace();
				}
				debug.debug("download file:" + imagePath);
			}
		}
	}

	/**
	 * 从SD卡获取Dish logo图片存放的地址
	 * */
	private void setDishLogoSrc(int length) {
		dishPicPaths = new String[length];
		if (flag && GlobalData.rscb != null) {
			for (int i = 0; i < length; i++) {
				String ShopLogoPath = GlobalData.dirPath
						+ "Dish/"
						+ DownManager.getImageFileName(GlobalData.rscb
								.getDishesBeanList().get(i).getPic());
				dishPicPaths[i] = ShopLogoPath;
			}
		} else if (!flag && GlobalData.rcdb != null) {
			for (int i = 0; i < length; i++) {
				String ShopLogoPath = GlobalData.dirPath
						+ "Dish/"
						+ DownManager.getImageFileName(GlobalData.rcdb
								.getDishesBeanList().get(i).getPic());
				dishPicPaths[i] = ShopLogoPath;
			}
		}
	}

}
